<?php

namespace MoChat\Salesman\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use TheSeer\Tokenizer\Exception;
use Hyperf\Command\Annotation\Command;

/**
 * @Command
 */
class SalesmanCommand extends HyperfCommand
{

    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('salesman');
    }

    public function configure()
    {
        parent::configure();
        $this->addOption('clear', 'C', InputArgument::OPTIONAL, '清除redis', 0);
        $this->setDescription('业务员同步');
    }

    public function handle()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        $clear = $this->input->getOption('clear');
        if ($clear) {
            $redis->del('SalesmanCommand_key');
        }
        $bool = $redis->get('SalesmanCommand_key');
        if ($bool) {
            $this->line('上一个业务员同步脚本程序正在执行中', 'info');
        } else {
            $redis->set('SalesmanCommand_key', true);
            $maxId = $redis->get('SalesTaskCommand_key_max_id');
            $maxId = $maxId ?: 0;
            Db::beginTransaction();
            try {
                $salesman = Db::connection('b2b')
                    ->table('salesman')->select(['*'])
                    ->where('ID','>',$maxId)
                    ->limit(50)
                    ->get()->toArray();
                if (empty($salesman)){
                    $redis->set('SalesTaskCommand_key_max_id', 0);
                }
                if (!empty($salesman)){
                    foreach ($salesman as $item){
                        Db::table('salesman')->updateOrInsert(['id'=>$item->ID],[
                            'name'=>$item->USER_NAME,
                            'mobile'=>$item->MOBILE,
                            'password'=>$item->PASSWORD_,
                            'salesman_group_id'=>$item->SALESMAN_GROUP_ID,
                            'salt'=>$item->SALT,
                            'status'=>$item->STATUS_,
                            'created_at'=>$item->CREATE_TIME,
                            'updated_at'=>$item->UPDATE_TIME
                        ]);
                    }
                    $lastSalesman = end($salesman);
                    $maxId=$lastSalesman->ID;
                    $redis->set('SalesTaskCommand_key_max_id', $maxId);
                }
                Db::commit();
            } catch (\Throwable $throwable) {
                Db::rollBack();
            }
            $redis->del('SalesmanCommand_key');
            $this->line('业务员同步处理完成', 'info');
        }
    }
}
